// 2020-6-20
// import urlConfig from "./siteinfo.js"
// 2020-7-4
let siteinfo = require('./siteinfo.js');
import Vue from 'vue'
//默认请求配置
const requestConfig = {
	header: {
		'content-type': 'application/x-www-form-urlencoded',
	},
	method: 'POST',
	timeout: 30000, // 超时时间，单位 ms
	dataType: 'JSON', // 如果设为 json，会尝试对返回的数据做一次 JSON.parse ｜ JSON.parse() 方法用于将一个 JSON 字符串转换为对象。
	responseType: 'text', // 设置响应的数据类型。合法值：text、arraybuffer
	sslVerify: true, // 验证 ssl 证书 ｜ 仅App安卓端支持（HBuilderX 2.3.3+）
	withCredentials: false // 跨域请求时是否携带凭证（cookies）｜仅H5支持（HBuilderX 2.6.15+）
}

function getroot(url) {
	return siteinfo.root
}
// 处理url
function getURLString(url) {
	let fmtUrl = siteinfo.siteroot + url
	return fmtUrl
}

function UPLOAD(url, config = {}) {
	let options = {};
	//请求配置处理
	options.header = Object.assign(requestConfig.header, config.header);
	if (uni.getStorageSync('token')) {
		options.header['Authori-zation'] = uni.getStorageSync('token');
	}else{
		options.header['Authori-zation'] = '';
	}
	if (uni.getStorageSync('shop')) {
		options.header['shop-id'] = uni.getStorageSync('shop').shop_id;
	}
	options.url = getURLString(url);
	options.filePath = config.filePath;
	var formData = {
		name: config.filePath
	};
	options.formData = Object.assign(formData, config.data);
	options.formData['uniacid'] = siteinfo.uniacid;
	return uploadRequest(options);
};
// 上传文件
function uploadRequest(options = {}) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: options.url,
			header: options.header,
			filePath: options.filePath,
			name: 'file',
			formData: options.formData,
			success: (res) => {
				// 成功返回数据
				if (res.data != []) {
					try {
						var data = JSON.parse(res.data);
						if (data.code == 500) {
							uni.setStorageSync('token',false);
							uni.showModal({
								title: '您未登录',
								content: '是否现在登录？',
								confirmText: '立即登录',
								success(e) {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/login/login?code=500'
										})
									} else {
										uni.navigateBack({

										})
									}
								}
							})
							return;
						} else if (data.code == 501) {
							uni.showModal({
								title: '您未授权手机号',
								content: '授权手机号后方可体验本项目',
								confirmText: '立即授权',
								success(e) {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/login/login?code=501'
										})
									} else {
										uni.navigateBack({

										})
									}
								}
							})
							return;
						} else if (data.code == 0) {
							uni.showToast({
								title: data.msg,
								icon: 'none'
							})
							resolve(JSON.parse(res.data)) // 转换为json
						} else {
							resolve(JSON.parse(res.data)) // 转换为json
						}
					} catch (e) {}
				}

				// 当返回数据为空
				if (res.data == []) {
					console.group()
					console.error("检查请求URL")
					console.warn("NULL")
					console.log(res)
					console.groupEnd()
				}
			},
			fail(err) {
				reject(err)
			},
			complete() {

			}
		})
	}).catch(err => console.error('请求错误:%o', err))
}
// post请求
function POST(url, config = {},showToast = true) {
	let options = {};
	options.showToast = showToast;
	//不管请求参数中传入的method是什么,全部改为POST
	options.method = "POST";
	//请求配置处理
	options.header = Object.assign(requestConfig.header, config.header);

	// #ifdef H5
	var api_name = '';
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		api_name = 'wechat'
	} else {
		api_name = 'wap'
	}
	// #endif
	// #ifdef APP-PLUS
	var api_name = 'android';
	// #endif
	// #ifdef MP-WEIXIN
	var api_name = 'wxapp';
	// #endif
	options.header['api-name'] = api_name;
	options.timeout = config.timeout || requestConfig.timeout;
	options.dataType = config.dataType || requestConfig.dataType;
	options.responseType = config.responseType || requestConfig.responseType;
	options.sslVerify = config.sslVerify || requestConfig.sslVerify;
	options.withCredentials = config.withCredentials || requestConfig.withCredentials;
	options.url = getURLString(url);
	options.data = Object.assign({}, config.data);
	if (uni.getStorageSync('token')) {
		options.header['Authori-zation'] = uni.getStorageSync('token');
	}else{
		options.header['Authori-zation'] = '';
	}
	if (uni.getStorageSync('shop')) {
		options.header['shop-id'] = uni.getStorageSync('shop').shop_id;
	}
	return request(options);
};

// get请求
function GET(url, config = {},showToast = true) {
	let options = {};
	//不管请求参数中传入的method是什么,全部改为GET
	options.method = "GET";
	options.showToast = showToast;
	//请求配置处理
	options.header = Object.assign(requestConfig.header, config.header);
	options.timeout = config.timeout || requestConfig.timeout;
	options.dataType = config.dataType || requestConfig.dataType;
	options.responseType = config.responseType || requestConfig.responseType;
	options.sslVerify = config.sslVerify || requestConfig.sslVerify;
	options.withCredentials = config.withCredentials || requestConfig.withCredentials;
	// #ifdef H5
	var api_name = 'wap';
	// #endif
	// #ifdef APP-PLUS
	var api_name = 'android';
	// #endif
	// #ifdef MP-WEIXIN
	var api_name = 'wxapp';
	// #endif
	options.header['api-name'] = api_name;
	options.url = getURLString(url);
	options.data = Object.assign({}, config.data);
	if (uni.getStorageSync('token')) {
		options.header['Authori-zation'] = uni.getStorageSync('token');
	}
	if (uni.getStorageSync('shop')) {
		options.header['shop-id'] = uni.getStorageSync('shop').shop_id;
	}
	return request(options);
};
// 发送请求
function request(options = {}) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: options.url,
			data: options.data,
			header: options.header,
			method: options.method,
			timeout: options.timeout,
			dataType: options.dataType,
			responseType: options.responseType,
			sslVerify: options.sslVerify,
			withCredentials: options.withCredentials,
			success: (res) => {
				uni.hideLoading()
				// 成功返回数据
				if (res.data != []) {
					try {
						var data = res.data;
						if (typeof data == 'string') {
							data = JSON.parse(data);
						}
						if (data.code == 500) {
							uni.setStorageSync('token',false);
							// uni.switchTab({
							// 	url:'/pages/me/me'
							// })
							uni.showModal({
								title: '您未登录',
								content: '是否现在登录？',
								confirmText: '立即登录',
								success(e) {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/login/login?code=500'
										})
									} else {
										uni.navigateBack({

										})
									}
								}
							})
							return;
						} else if (data.code == 501) {
							uni.showModal({
								title: '您未授权手机号',
								content: '授权手机号后方可体验本项目',
								confirmText: '立即授权',
								success(e) {
									if (e.confirm) {
										uni.navigateTo({
											url: '/pages/login/login?code=501'
										})
									} else {
										uni.navigateBack({

										})
									}
								}
							})
							return;
						} else if (data.code == 0) {
							if(options.showToast){
								uni.showToast({
									title: data.info,
									icon: 'none'
								});
							}
							resolve(data) // 转换为json
						} else {
							resolve(data) // 转换为json
						}
					} catch (e) {}
				}
				// 当返回数据为空
				if (res.data == []) {
					console.group()
					console.error("检查请求URL")
					console.warn("NULL")
					console.log(res)
					console.groupEnd()
				}
			},
			fail(err) {
				reject(err)
			},
			complete() {

			}
		})
	}).catch(err => console.error('请求错误:%o', err))
}

export default {
	getURLString, // this.$req.getURLString("upload") 调用上传文件地址
	getroot,
	UPLOAD,
	POST,
	GET
}
